package com.levi.http;

import android.text.TextUtils;

import com.levi.utils.log.LogUtils;

import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by Levi on 2018/3/13.
 */

public class HttpClientManager {
    private static final String TAG = "HttpClientManager";
    private static HttpClientManager sInstance;

    public static HttpClientManager getInstance() {
        if (sInstance == null) {
            synchronized (HttpClientManager.class) {
                if (sInstance == null) {
                    sInstance = new HttpClientManager();
                }
            }
        }
        return sInstance;
    }

    //------------------------------------------------------------------------------------------------------------------

    private OkHttpClient mHttpClient;

    private HttpClientManager() {

    }

    public void init(OkHttpClient.Builder builder) {
        mHttpClient = builder.retryOnConnectionFailure(false).build();
//        mHttpClient = builder.build();
//        sClient = builder.retryOnConnectionFailure(false).build();
        LogUtils.i(TAG, "HttpClientManager: OkHttpClient initialized");
    }

    public Call newCall(Request request) {
        if (mHttpClient == null) {
            throw new IllegalStateException("http client did not init");
        }
        return mHttpClient.newCall(request);
    }

    public void cancelGroup(String groupTag) {
        if (mHttpClient != null && !TextUtils.isEmpty(groupTag)) {
            LogUtils.i(TAG, "HttpClientManager: cancelGroup[" + groupTag + "]");
            Dispatcher dispatcher = mHttpClient.dispatcher();
            synchronized (dispatcher) {
                for (Call call : dispatcher.queuedCalls()) {
                    if (groupTag.equals(call.request().tag())) {
                        call.cancel();
                    }
                }
                for (Call call : dispatcher.runningCalls()) {
                    if (groupTag.equals(call.request().tag())) {
                        call.cancel();
                    }
                }
            }
        }
    }

    public void release() {
        if (mHttpClient != null) {
            LogUtils.i(TAG, "HttpClientManager: shutdown");
            mHttpClient.dispatcher().executorService().shutdown();
            mHttpClient.connectionPool().evictAll();
            mHttpClient = null;
        }
    }
}
